package com.easy.stock.spider;

import java.util.Properties;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpiderDriver {
	
	protected static Log LOG = LogFactory.getLog("spider");
	
	/**
	 * 设置命令行参数
	 */
	@SuppressWarnings("static-access")
	private static Options addCommandOptions() {
		Options options = new Options();
		options.addOption(new Option("help", "print this message"));
		
		options.addOption(OptionBuilder.withArgName("spider name").hasArg()
								.withDescription("spring bean name of the spider")
								.create("spiderName"));
		
		options.addOption(OptionBuilder.withArgName("property=value")
    			.hasArgs(2)
    			.withValueSeparator()
    			.withDescription( "use value for given property" )
    			.create( "D" ));
		
		return options;
	}
	
	
	public static void main(String args[]) throws Exception {
		
		// 解析参数
		Options options = addCommandOptions();
		CommandLineParser parser = new BasicParser();
		CommandLine line = parser.parse(options, args);
		if(line.hasOption("help") || !line.hasOption("spiderName")) {
			HelpFormatter formatter = new HelpFormatter();
			formatter.printHelp(SpiderDriver.class.getSimpleName(), options );
			return;
		}
		
		String spiderName = line.getOptionValue("spiderName");
		Properties props = line.getOptionProperties("D");
		LOG.info("parse args for "+spiderName+" success!");
		
		// 加载spring环境
		ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
		
		// 启动爬虫
		Spider spider = (Spider)context.getBean(spiderName);
		if(spider==null) {
			LOG.error("can't find spider, name="+spiderName);
			return;
		}
		
		LOG.info("start spider, name="+spiderName);
		spider.setup(props);
		int ret = spider.crawl();
		LOG.info("spider crawl finished, name="+spiderName+", ret="+ret);
	}

}
